package com.pirestupppai.ui.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.adapter.PsListAdapter;
import com.pirestupppai.adapter.SelectFolderAdapter;
import com.pirestupppai.adapter.SelectPictureAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.SelectFolder;
import com.pirestupppai.bean.SelectPicture;
import com.pirestupppai.common.Constant;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.utils.FileUtil;
import com.pirestupppai.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscription;
import rx.functions.Action1;

import static com.pirestupppai.rxbus.RxBus.RXBUS_FINISH_ACTIVITY;


/**
 * 图片选择
 *
 * @author: xiaoluo
 * @date: 2017-01-16 16:21
 */
public class SelectPictureActivity extends BaseActivity {
    private final static String TAG = SelectPictureActivity.class.getSimpleName();

    @BindView(R.id.parent)
    RelativeLayout parentLayout;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.folder_btn)
    TextView folderBtn;
    @BindView(R.id.next_btn)
    TextView nextBtn;
    @BindView(R.id.select_count)
    TextView countTv;
    @BindView(R.id.image_select_grid)
    GridView selectGridView;
    @BindView(R.id.select_next_layout)
    RelativeLayout nextLayout;

    private static final int LOADER_ALL = 0;             // 选择全部图片
    private static final int LOADER_CATEGORY = 1;        // 选择某个文件夹下的图片
    private static final int CODE_REQUEST_CAMERA = 2;    // 手机拍照请求码

    private int mMaxCount = 2;  // 最大选择数

    private SelectPictureAdapter mPictureAdapter;
    private List<SelectPicture> images = new ArrayList<SelectPicture>();
    // 结果数据
    private ArrayList<String> resultList = new ArrayList<String>();
    // 文件夹数据
    private ArrayList<SelectFolder> mResultFolder = new ArrayList<SelectFolder>();

    private File mTmpFile;

    private View mFolderPopView;
    private PopupWindow mFolderPopupWindow;
    private ListView mImageListView;
    private SelectFolderAdapter mFolderAdapter;
    private boolean hasFolderGened = false;
    private int mReleaseType = 110;
    private int mAskId = -1;
    private int mPsType;

    private Subscription mSubscription;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_select_pic;
    }

    @Override
    protected void initViews() {
        mReleaseType = getIntent().getIntExtra(Constant.IntentKey.RELEASE_TYPE, 110);
        mPsType = getIntent().getIntExtra(Constant.IntentKey.PS_TYPE, PsListAdapter.PS_TYPE_REPLY_NOW);
        mAskId = getIntent().getIntExtra(Constant.IntentKey.PARENT_ID, -1);
        if (mReleaseType == Constant.SELECT_TYPE_ASK) {
            mMaxCount = 2;
        } else {
            mMaxCount = 1;
        }

        mFolderAdapter = new SelectFolderAdapter(mContext);
        mPictureAdapter = new SelectPictureAdapter(mContext);

        selectGridView.setAdapter(mPictureAdapter);

        selectGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onGlobalLayout() {

                        final int width = selectGridView.getWidth();
                        final int height = selectGridView.getHeight();

                        final int desireSize = getResources()
                                .getDimensionPixelOffset(
                                        R.dimen.multi_image_slect_size);
                        final int numCount = width / desireSize;
                        selectGridView.setNumColumns(numCount);
                        final int columnSpace = getResources()
                                .getDimensionPixelOffset(
                                        R.dimen.multi_image_select_space_size);
                        int columnWidth = (width - columnSpace * (numCount - 1))
                                / numCount;
                        mPictureAdapter.setItemSize(columnWidth);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            selectGridView.getViewTreeObserver()
                                    .removeOnGlobalLayoutListener(this);
                        } else {
                            selectGridView.getViewTreeObserver()
                                    .removeGlobalOnLayoutListener(this);
                        }
                    }
                });

        if (mFolderPopupWindow == null) {
            createPopupFolder();
        }

        getSupportLoaderManager()
                .restartLoader(LOADER_ALL, null,
                        mLoaderCallback);

    }

    @Override
    protected void initListeners() {
        selectGridView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView,
                                            View view, int i, long l) {
                        // 如果显示照相机，则第一个Grid显示为照相机
                        if (i == 0) {
                            if (resultList.size() < mMaxCount) {
                                showCameraAction();
                            } else {
                                Utils.showToast("最多选择" + mMaxCount + "张图片");
                            }

                        } else {
                            // 正常操作
                            SelectPicture image = (SelectPicture) adapterView
                                    .getAdapter().getItem(i);
                            selectImageFromGrid(image, view);
                        }
                    }
                });

        folderBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        nextLayout.setOnClickListener(this);
    }

    @Override
    protected void initLogic() {
        //注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_FINISH_ACTIVITY, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        finish();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.folder_btn:
                if (mFolderPopupWindow.isShowing()) {
                    mFolderPopupWindow.dismiss();
                } else {
                    mFolderPopupWindow.showAtLocation(parentLayout, Gravity.CENTER, 0, 0);
                    mFolderPopupWindow.setFocusable(true);
                    mFolderPopupWindow.update();

                    mFolderPopupWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            // TODO Auto-generated method stub
                            mFolderPopupWindow.setFocusable(false);
                            mFolderPopupWindow.dismiss();
                            return true;
                        }

                    });

                    int index = mFolderAdapter.getSelectIndex();
                    index = index == 0 ? index : index - 1;
                    mImageListView.setSelection(index);
                }
                break;
            case R.id.select_next_layout:
                if (resultList.size() > 0) {
                    if (mReleaseType != Constant.SELECT_TYPE_REVISE) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putStringArrayList(Constant.IntentKey.SELECT_LIST, resultList);
                        bundle.putInt(Constant.IntentKey.RELEASE_TYPE, mReleaseType);
                        bundle.putInt(Constant.IntentKey.PS_TYPE, mPsType);
                        bundle.putInt(Constant.IntentKey.PARENT_ID, mAskId);
                        intent.putExtras(bundle);
                        intent.setClass(mContext, ReleaseActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra(Constant.IntentKey.SELECT_LIST, resultList.get(0));
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                } else {
                    Utils.showToast("还未选择图片");
                }
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }



    /**
     * 选择相机
     */
    private void showCameraAction() {
        // 设置系统相机拍照后的输出路径为DCIM目录
        mTmpFile = FileUtil.createTmpFile(mContext);
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(this.getPackageManager()) != null) {
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(mTmpFile));
            startActivityForResult(cameraIntent, CODE_REQUEST_CAMERA);
        } else {
            Utils.showToast("没有相机");
        }
    }

    /**
     * 创建弹出的ListView
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressLint("NewApi")
    private void createPopupFolder() {
        mFolderPopView = LayoutInflater.from(mContext)
                .inflate(R.layout.ppw_select_image_folder, null);
        mImageListView = (ListView) mFolderPopView.findViewById(R.id.image_folder_list);
        mFolderPopupWindow = new PopupWindow(mFolderPopView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mFolderPopupWindow.setWidth(-1);
        mFolderPopupWindow.setHeight(-1);
        mFolderPopupWindow.setOutsideTouchable(true);

        mImageListView.setAdapter(mFolderAdapter);

        mImageListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView,
                                            View view, int i, long l) {
                        if (i == 0) {
                            getSupportLoaderManager()
                                    .restartLoader(LOADER_ALL, null,
                                            mLoaderCallback);
                            folderBtn.setText("全部图片");
                        } else {
                            SelectFolder folder = (SelectFolder) adapterView.getAdapter()
                                    .getItem(i);
                            if (null != folder) {
                                Bundle args = new Bundle();
                                args.putString("path", folder.path);
                                getSupportLoaderManager()
                                        .restartLoader(LOADER_CATEGORY, args,
                                                mLoaderCallback);
                                folderBtn.setText(folder.name);
                            }
                        }
                        mFolderAdapter.setSelectIndex(i);
                        mFolderPopupWindow.dismiss();

                        // 滑动到最初始位置
                        selectGridView.smoothScrollToPosition(0);
                    }
                });

        // 处理PopupWindow显示后，返回键无法响应
        mImageListView.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                mFolderPopupWindow.dismiss();
                return false;
            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        // 相机拍照完成后，返回图片路径
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CODE_REQUEST_CAMERA) {

                // 更新相册后通知系统扫描更新
                Intent intentSystem = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(mTmpFile);
                intentSystem.setData(uri);
                mContext.sendBroadcast(intentSystem);

                resultList.add(mTmpFile.getAbsolutePath());
                // 调用相机拍照后，再次扫描手机内的图片
                getSupportLoaderManager().initLoader(0, null, mLoaderCallback);
//                getSupportLoaderManager().initLoader(0, null, mFolderCallback);
                folderBtn.setText("全部图片");

                countTv.setText(resultList.size() + "");
            }
        }
    }

    /**
     * 选择图片操作
     *
     * @param image
     */
    private void selectImageFromGrid(SelectPicture image, View imgView) {
        if (image != null) {
            // 多选模式
            if (resultList.contains(image.path)) {
                resultList.remove(image.path);
                // 移除

                if (resultList.size() != 0) {

                } else {

                }
            } else {
                // 添加
                View view = new View(this);

                // 判断选择数量问题
                if (mMaxCount == resultList.size()) {
                    Utils.showToast("最多选择" + mMaxCount + "张图片");
                    return;
                }

                resultList.add(image.path);

            }
            mPictureAdapter.select(image);
            countTv.setText(resultList.size() + "");
        }
    }


    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if (id == LOADER_ALL) {
                CursorLoader cursorLoader = new CursorLoader(mContext,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        IMAGE_PROJECTION, null, null, IMAGE_PROJECTION[2]
                        + " DESC");
                return cursorLoader;
            } else if (id == LOADER_CATEGORY) {
                CursorLoader cursorLoader = new CursorLoader(mContext,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        IMAGE_PROJECTION, IMAGE_PROJECTION[0] + " like '%"
                        + args.getString("path") + "%'", null,
                        IMAGE_PROJECTION[2] + " DESC");
                return cursorLoader;
            }

            return null;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                if (images != null && images.size() > 0) {
                    images.clear();
                }
                int resultLength = resultList.size();
                for (int i = 0; i < resultLength; i++) {
                    images.add(new SelectPicture(resultList.get(i), "", 0));
                }
                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    out:
                    do {
                        String path = data.getString(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                        String name = data.getString(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                        long dateTime = data.getLong(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        SelectPicture image = new SelectPicture(path, name,
                                dateTime);
                        //判断是否是已选择的图片，因为已经置顶，如果是则不填充
                        for (int i = 0; i < resultLength; i++) {
                            if (resultList.get(i).equals(path)) {
                                images.get(i).name = name;
                                images.get(i).time = dateTime;
                                continue out;
                            }
                        }
                        images.add(image);

                    } while (data.moveToNext());

                    mPictureAdapter.setData(images);
                    // 设定默认选择
                    if (resultList != null && resultList.size() > 0) {
                        mPictureAdapter.setDefaultSelected(resultList);
                    }

                    //初始化文件目录
                    if (!hasFolderGened) {
                        getSupportLoaderManager().initLoader(0, null, mFolderCallback);
                    }
                }
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

    private LoaderManager.LoaderCallbacks<Cursor> mFolderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            CursorLoader cursorLoader = new CursorLoader(mContext,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    IMAGE_PROJECTION, null, null, IMAGE_PROJECTION[2]
                    + " DESC" +
                    "");
            return cursorLoader;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    do {
                        String path = data.getString(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                        String name = data.getString(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                        long dateTime = data.getLong(data
                                .getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        SelectPicture image = new SelectPicture(path, name,
                                dateTime);
                        // 获取文件夹名称
                        File imageFile = new File(path);
                        File folderFile = imageFile.getParentFile();
                        SelectFolder folder = new SelectFolder();
                        folder.name = folderFile.getName();
                        folder.path = folderFile.getAbsolutePath();
                        folder.cover = image;
                        if (!mResultFolder.contains(folder)) {
                            List<SelectPicture> imageList = new ArrayList<SelectPicture>();
                            imageList.add(image);
                            folder.images = imageList;
                            mResultFolder.add(folder);
                            // 判断进入时是那个相册被选中
//                            if (folderFile.getPath().equals(jumpPath)) {
//                                mFolderAdapter.setSelectIndex(mResultFolder.size());
//                            }
                        } else {
                            // 更新
                            SelectFolder f = mResultFolder.get(mResultFolder
                                    .indexOf(folder));
                            f.images.add(image);
                        }
                    } while (data.moveToNext());
                    mFolderAdapter.setData(mResultFolder);
                    hasFolderGened = true;
                }
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };
}
